<template>
    <div>
        <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>权限管理</el-breadcrumb-item>
        <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
    <el-button type="success" @click='addRole'>添加角色</el-button>
    <!-- 添加角色模态框 -->
    <el-dialog
            title="添加角色"
            :visible.sync="rolesVisible"
            @close='resetForm("addRoleRef")'
            >
            <el-form ref='addRoleRef' :rules='addRoleRules' :model="addRoleForm" label-width="80px">
             <el-form-item label="角色名称" prop='roleName'>
                <el-input v-model="addRoleForm.roleName"></el-input>
             </el-form-item>
             <el-form-item label="角色描述" prop='roleDesc'>
                <el-input v-model="addRoleForm.roleDesc"></el-input>
             </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
              <el-button @click="rolesVisible = false">取 消</el-button>
              <el-button type="primary" @click=checkRole>确 定</el-button>
            </span>
    </el-dialog>
  <el-table :data="rolesList"  border
   style="width: 100%">
   <!-- 展开列 -->
   <el-table-column type="expand">
       <template slot-scope="props">
       <el-row :class="['tablebtn' , 'verticle', index===0?'tabletop':'']"  v-for='(item,index) in props.row.children' :key='item.id' >
         <!-- 显示一级权限 -->
         <el-col :span="5">
            <el-tag >{{item.authName}}</el-tag>
            <i class="el-icon-caret-right"></i>
         </el-col>
         <!-- 显示二级三级权限 -->
         <el-col :span="19">
             <el-row :class="[i===0?'':'tabletop','verticle']" v-for='(val,i) in item.children' :key=val.id>
                 <el-col :span='5'>
                     <el-tag type='success' >{{val.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
                 </el-col>
                <el-col :span='15' @close='closeRight'>
                    <el-tag type="warning" closable v-for="tag in val.children" :key='tag.id' @close='closeTag(tag,props.row)'>{{tag.authName}}</el-tag>
                </el-col>
             </el-row>
         </el-col>
        </el-row>
      </template>
    </el-table-column>
    <!-- 列表信息 -->
   <el-table-column
      type="index"
      label="序号"
      >
    </el-table-column>
    <el-table-column
      prop="roleName"
      label="角色名称"
      >
    </el-table-column>
    <el-table-column
      prop="roleDesc"
      label="角色描述"
      >
    </el-table-column>
        <el-table-column  label="操作">
                <!-- 操作按钮 -->
                <template slot-scope="scopes">
                <el-row>
                    <el-tooltip effect="dark" content="修改角色" placement="top" :enterable='false'>
                    <!-- 修改角色 -->
                        <el-button type="primary" size='mini' icon="el-icon-edit" @click='toEditRoles(scopes.row.id)'>编辑</el-button>
                    </el-tooltip>
                    <!-- 删除角色 -->
                    <el-tooltip effect="dark" content="删除角色" placement="top" :enterable='false'>
                        <el-button type="danger" size='mini' icon="el-icon-delete" @click='toDeleteRoles(scopes.row.id)'>删除</el-button>
                    </el-tooltip>
                    <!-- 分配角色 -->
                    <el-tooltip effect="dark" content="分配权限" placement="top" :enterable='false'>
                        <el-button type="warning" size='mini' icon="el-icon-setting" @click='toSetting(scopes.row)'>分配权限</el-button>
                    </el-tooltip>
                </el-row>
                </template>
        </el-table-column>
  </el-table>
        </el-card>
        <!-- 修改角色模态框 -->
    <el-dialog
            title="修改角色"
            :visible.sync="editVisible"
            @close='resetForm("editRoleRef")'
            >
            <el-form ref='editRoleRef' :rules='addRoleRules' :model="editRoleForm" label-width="80px">
             <el-form-item label="角色名称" prop='roleName'>
                <el-input v-model="editRoleForm.roleName"></el-input>
             </el-form-item>
             <el-form-item label="角色描述" prop='roleDesc'>
                <el-input v-model="editRoleForm.roleDesc"></el-input>
             </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
              <el-button @click="editVisible = false">取 消</el-button>
              <el-button type="primary" @click='toEdit'>确 定</el-button>
            </span>
    </el-dialog>
    <!-- 修改权限 -->
    <el-dialog
            title="修改权限"
            :visible.sync="editRightsVisible"
            @close='clearRoleRights'
            >
            <el-form  label-width="50px">
                <el-tree :data="editRightsList" :props="defaultRights" node-key='id'
                default-expand-all show-checkbox :default-checked-keys='rightsArry' ref='editRoleRightsRef'></el-tree>
            </el-form>
            <span slot="footer" class="dialog-footer">
              <el-button @click="editRightsVisible = false">取 消</el-button>
              <el-button type="primary" @click='allotRights'>确 定</el-button>
            </span>
    </el-dialog>
    </div>
</template>

<script>
export default {
  data () {
    return {
      rolesList: [],
      addRoleForm: {
        roleName: '',
        roleDesc: ''
      },
      editRoleForm: {
        roleId: '',
        roleName: '',
        roleDesc: ''
      },
      defaultRights: {
        children: 'children',
        label: 'authName'
      },
      editRightsList: [],
      rightsArry: [],
      rightsId: 0,
      rolesVisible: false,
      editVisible: false,
      editRightsVisible: false,
      // 角色验证规则
      addRoleRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    // 获取数据
    this.getRoles()
  },
  methods: {
    async getRoles () {
      const data = await this.$http.get('roles')
      //   将数据赋值给rolelist
      this.rolesList = data.data
    },
    // 点击添加角色
    addRole () {
      this.rolesVisible = true
    },
    // 查询角色
    async toEditRoles (id) {
      this.editVisible = true
      const data = await this.$http.get('roles/' + id)
      this.editRoleForm.roleId = data.data.roleId
      this.editRoleForm.roleName = data.data.roleName
      this.editRoleForm.roleDesc = data.data.roleDesc
    },
    // 验证添加角色
    checkRole () {
      this.$refs.addRoleRef.validate(async (valid) => {
        if (!valid) {
          return this.$Message.error('信息输入错误，请重新输入正确格式')
        } else {
        // 发送添加用户信息请求
          const data = await this.$http.post('roles', this.addRoleForm)
          if (data.meta.status === 201) {
            this.$message.success('创建角色成功')
            this.rolesVisible = false
            this.getRoles()
          } else {
            this.$Message.error('创建角色失败')
          }
        }
      })
    },
    // 验证角色修改
    toEdit () {
      this.$refs.editRoleRef.validate(async (valid) => {
        if (!valid) {
          return this.$Message.error('信息输入错误，请重新输入正确格式')
        } else {
        // 发送添加用户信息请求
          const data = await this.$http.put('roles/' + this.editRoleForm.roleId, this.editRoleForm)
          if (data.meta.status === 200) {
            this.$message.success('修改角色成功')
            this.editVisible = false
            this.getRoles()
          } else {
            this.$Message.error('修改角色失败')
          }
        }
      })
    },
    // 重置表单
    resetForm (val) {
      this.$refs[val].resetFields()
    },
    // 清空上一个角色权限影响
    clearRoleRights () {
      this.rightsArry = []
    },
    closeRight () {
    // 删除权限
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 删除角色
    toDeleteRoles (id) {
    // 删除用户
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        await this.$http.delete('roles/' + id)
        this.getRoles()
        this.$Message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$Message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    async toSetting (role) {
      this.rightsId = role.id
      //  获取所有权限
      this.editRightsVisible = true
      const data = await this.$http.get('rights/tree')
      console.log(data.data)
      this.editRightsList = data.data
      //   获取角色查询权限id
      this.getRolesRight(role, this.rightsArry)
    },
    // 使用递归函数获取角色的id
    getRolesRight (value, arr) {
    // 为三级权限时
      if (!value.children) {
        //   将id放入arr中
        return arr.push(value.id)
      } else {
        //   当不为三级权限时
        value.children.forEach(item => {
          this.getRolesRight(item, arr)
        })
      }
    },
    // 分配权限
    async allotRights () {
      // 全选中的权限所形成的的数组
      const allkeys = this.$refs.editRoleRightsRef.getCheckedKeys()
      // 获取半选权限所形成的的数组
      const halfkeys = this.$refs.editRoleRightsRef.getHalfCheckedKeys()
      const keys = [...allkeys, ...halfkeys]
      const keyString = keys.join(',')
      console.log(keyString)
      // 发送授权请求
      const data = await this.$http.post('roles/' + this.rightsId + '/rights', {
        rids: keyString
      })
      if (data.meta.status === 200) {
        this.$message.success('分配权限成功')
        this.editRightsVisible = false
      } else {
        return this.$message.error('分配权限失败')
      }
    },
    // 删除三级权限tag
    closeTag (tag, row) {
    // 删除用户
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const data = await this.$http.delete(`roles/${row.id}/rights/${tag.id}`)
        row.children = data.data
        this.$Message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$Message({
          type: 'info',
          message: '已取消删除'
        })
      })
    }
  }
}

</script>

<style lang="less" scoped>
.el-tag {
    margin:10px;
}
.tablebtn {
    border-bottom: 1px solid #ccc;
}
.tabletop {
    border-top: 1px solid #ccc;
}
.verticle {
    display: flex;
    align-items: center;
}
</style>
